package net.wicp.tams.common.jdbc;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.google.protobuf.ProtocolStringList;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.CollectionUtil;
import net.wicp.tams.common.apiext.jdbc.JdbcData;
import net.wicp.tams.common.apiext.jdbc.JdbcDatas;
import net.wicp.tams.common.apiext.jdbc.MySqlAssit;

@Slf4j
public abstract class MySqlAssitExt extends MySqlAssit {
	private static String splitChar = ",";

	public static Result upsetDataMysqlDriver(Connection conn, String db, String tb, String[] cols, String datas) {
		try {
			conn.setAutoCommit(false);
			String colStr = CollectionUtil.arrayJoin(cols, ",");
			PreparedStatement ins = conn.prepareStatement(
					String.format("load data local infile '' replace into table %s fields terminated by '%s' (%s)",
							String.format("%s.%s", db, tb), splitChar, colStr));
			InputStream is = new ByteArrayInputStream(datas.getBytes());
			((com.mysql.jdbc.Statement) ins).setLocalInfileInputStream(is);
			ins.execute();
			conn.commit();
			return Result.getSuc();
		} catch (SQLException e) {
			log.error("批处理出错", e);
			return Result.getError(e.getMessage());
		}
	}

	public static Result upsetDataMysqlDriver(Connection conn, JdbcDatas datas) {
		ProtocolStringList keysList = datas.getColsList();
		String[] keys = keysList.toArray(new String[keysList.size()]);
		StringBuilder sb = new StringBuilder();
		for (JdbcData jdbcData : datas.getDatasList()) {
			for (String col : keysList) {
				sb.append(jdbcData.getValueMap().get(col) + splitChar);
			}
			sb.replace(sb.length() - 1, sb.length(), "\n");
		}
		return upsetDataMysqlDriver(conn, datas.getDb(), datas.getTb(), keys, sb.toString());
	}
}
